package logic

import (
	"context"
	"fmt"
	"zc2/model/mysql"
	"zc2/model/redis"
	"zc2/userrpc/internal/svc"
	"zc2/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("sendsmsUpdate" + in.Name)
	if get.Val() != in.Sendsms {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}
	var user mysql.User
	mysql.DB.Where("name=?", in.Name).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("没有该用户，请重新输入")
	}
	if user.Password != in.Oldpassword {
		return nil, fmt.Errorf("旧密码输入错误，请重新输入")
	}
	if in.Oldpassword == in.Newpassword {
		return nil, fmt.Errorf("旧密码和新密码不一致，请重新输入")
	}
	user.Password = in.Newpassword
	mysql.DB.Updates(&user)
	return &userrpc.UpdateResponse{Id: int64(user.ID)}, nil
}
